/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.module.properties;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import org.w3c.dom.NodeList;
import tal.drivechain.chain.ChainNode;
import tal.drivechain.system.PluginLoader;

/**
 *
 * @author Main
 */
public class CustomParser implements PropertyParser {
    private String className = null, parserName = null;
    private HashMap<String, String> attributes;
    private boolean requireBrackets = true;
    public String getPropertyType() {
        return "{" + className + "." + parserName + "}";
    }

    public void setAttribures(HashMap<String, String> attributes, NodeList childElements) throws IllegalArgumentException {
        className = attributes.get("class");
        if (className == null) {
            throw new IllegalArgumentException("missing attribute: class");
        }
        parserName = attributes.get("parser-name");
        if (parserName == null) {
            throw new IllegalArgumentException("missing attribute: parser-name");
        }

        String rb = attributes.get("require-brackets");
        if (rb!=null) {
            if (rb.equals("true"))
                requireBrackets = true;
            else if (rb.equals("false"))
                requireBrackets = false;
            else throw new IllegalArgumentException("Unknown require-brackets value: " + rb);
        }

        this.attributes = attributes;
    }

    public Object parseProperty(String prop) throws IllegalArgumentException {
        String methodName = "parse" + parserName.substring(0, 1).toUpperCase() + parserName.substring(1);
        Object obj;
        try {
            obj = PluginLoader.getClass(className).newInstance();
        } catch (InstantiationException ex) {
            throw new IllegalArgumentException("Can't instantiate custom parser for " + prop + ": " + ex.getMessage());
        } catch (IllegalAccessException ex) {
            throw new IllegalArgumentException("Illegal access to custom parser class for " + prop + ": " + ex.getMessage());
        }
        Method parser = null;
        try {
            parser = obj.getClass().getMethod(methodName, String.class, HashMap.class);
        } catch (NoSuchMethodException ex) {
            throw new IllegalArgumentException("Can't find a property parser - " + parserName + " in " + className + " (" + className + "." + methodName + ")");
        } catch (SecurityException ex) {
            throw new IllegalArgumentException("Error while looking for property parser - " + parserName + " in " + className + " (" + ex.getMessage() + ")");
        }

        try {
            prop = prop.trim();
            if (requireBrackets) {
                if (prop.charAt(0)=='{' && prop.charAt(prop.length()-1)=='}')
                    prop = prop.substring(1, prop.length()-1);
                else throw new IllegalArgumentException("Custom parser value must be surrounded by curly brackets ('{}')");
            }
            return parser.invoke(null, prop, attributes);
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
            throw new IllegalArgumentException("Error while trying to invoke custom property parser (" + parserName + "): " + ex.getMessage());
        } catch (InvocationTargetException ex) {
            ex.getTargetException().printStackTrace();
            throw new IllegalArgumentException("Error while trying to invoke custom property parser (" + parserName + "): " + ex.getTargetException().getMessage());
        }
    }

    public String propToString(Object prop, ChainNode context) {
        String methodName = parserName + "ToString";
        Object obj;
        try {
            obj = PluginLoader.getClass(className).newInstance();
        } catch (InstantiationException ex) {
            throw new IllegalArgumentException("Can't instantiate class " + prop + ": " + ex.getMessage());
        } catch (IllegalAccessException ex) {
            throw new IllegalArgumentException("Illegal access in class " + prop + ": " + ex.getMessage());
        }
        Method toString = null;
        try {
            toString =  obj.getClass().getMethod(methodName, Object.class, HashMap.class);
        } catch (NoSuchMethodException ex) {
            throw new IllegalArgumentException("Can't find a property parser - " + parserName + " in " + className + " (Window." + methodName + ")");
        } catch (SecurityException ex) {
            throw new IllegalArgumentException("Error while looking for property parser - " + parserName + " in " + className + " (" + ex.getMessage() + ")");
        }
        if (!Modifier.isStatic(toString.getModifiers()))
            throw new IllegalArgumentException("Error while trying to invoke custom property parser (" + parserName + "): Method " + toString.getName() + " is not static.");
        try {
            String val = (String)toString.invoke(null, prop, attributes);
            if (requireBrackets) return "{"+val+"}";
            else return val;
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
            throw new IllegalArgumentException("Error while trying to invoke custom property parser (" + parserName + "): " + ex.getMessage());
        } catch (InvocationTargetException ex) {
            ex.printStackTrace();
            throw new IllegalArgumentException("Error while trying to invoke custom property parser (" + parserName + "): " + ex.getTargetException().getMessage());
        }
    }    
}
